<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('项目情况') }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('项目名称')" prop="dealName">
        <el-input
          v-model="queryParams.dealName"
          :placeholder="$t('项目名称')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item :label="$t('部门')">
        <DeptSelect
          v-model="queryParams.dept"
          :placeholder="$t('部门')"
          filterable
          multiple
        />
      </el-form-item>
      <el-form-item :label="$t('项目负责人')" prop="personCharge">
        <UserSelect v-model="queryParams.personCharge" :placeholder="$t('项目负责人')" />
      </el-form-item>
      <el-form-item :label="$t('签约日期')" prop="initialSigningTime">
        <DatePicker v-model="initialSigningTimes" type="daterange" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t('搜索') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" type="warning" @click="calculation">{{ $t('更新人天') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          v-hasPermi="['anxin:dealSituation:export']"-->
      <!--          type="warning"-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="exportHandle"-->
      <!--        >{{ $t('导出') }}</el-button>-->
      <!--      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="dealSituationList" border tooltip-effect="darkTable" @sort-change="dataSort">
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50" fixed="left">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('项目名称')" align="center" prop="dealName" fixed="left" sortable="custom" min-width="230" show-overflow-tooltip />
      <el-table-column :label="$t('负责人')" align="center" prop="personChargeName" min-width="120" sortable="custom" show-overflow-tooltip />
      <el-table-column :label="$t('签约数量')" align="center" prop="contractQuantity" min-width="120" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link type="primary" class="money-text" @click="findContractSituation(scope.row)">
            <span>{{ scope.row.contractQuantity }}</span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('签约金额') + $t('(万)')" align="center" prop="contractAmount" min-width="120" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link type="primary" class="money-text" @click="findContractSituation(scope.row)">
            <span>{{ parseFloat(scope.row.contractAmount / 10000).toFixed(2) }}</span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('已收款') + $t('(万)')" align="center" prop="received" min-width="120" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link type="primary" class="money-text" @click="findCollectionSituation(scope.row, 'YSK')">
            <span>{{ parseFloat(scope.row.received / 10000).toFixed(2) }}</span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('人力成本') + $t('(万)')" align="center" prop="laborCost" min-width="120" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link type="primary" class="money-text" @click="queryUserDealWorkloadByMonth(scope.row)">
            <span>{{ parseFloat(scope.row.laborCost / 10000).toFixed(2) }}</span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('利润Est') + $t('(万)')" align="center" prop="profitEst" min-width="120" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="money-text">{{ parseFloat(scope.row.profitEst / 10000).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('利润Act') + $t('(万)')" align="center" prop="profitAct" min-width="120" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="money-text">{{ parseFloat(scope.row.profitAct / 10000).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('未收款') + $t('(万)')" align="center" prop="uncollected" min-width="120" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link type="primary" class="money-text" @click="findCollectionSituation(scope.row, 'WSK')">
            <span>{{ parseFloat(scope.row.uncollected / 10000).toFixed(2) }}</span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('坏账') + $t('(万)')" align="center" prop="badDebt" min-width="120" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link type="primary" class="money-text" @click="findCollectionSituation(scope.row, 'HZ')">
            <span>{{ parseFloat(scope.row.badDebt / 10000).toFixed(2) }}</span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('工作量(人天)')" align="center" prop="workload" min-width="120" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link type="primary" class="money-text" @click="queryUserDealWorkloadByMonth(scope.row)">
            <span>{{ parseFloat(scope.row.workload).toFixed(2) }}</span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('首次签约时间')" align="center" prop="initialSigningTime" min-width="120" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.initialSigningTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 签约合同 -->
    <el-dialog
      :title="dealName + $t('-签约合同列表')"
      :visible.sync="contractOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
      width="80%"
    >
      <el-table v-loading="oaContractLoading" :data="oaContractList" border tooltip-effect="darkTable">
        <el-table-column :label="$t('序号')" type="index" align="center" width="50" />
        <el-table-column :label="$t('合同名称')" align="center" prop="name" min-width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="link-type" @click="updateOaContractHandle(scope.row)">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('签约时间')" align="center" prop="signingTime" width="180" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.signingTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('签约金额') + $t('(万)')" align="center" prop="money" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="money-text">{{ parseFloat(scope.row.money / 10000).toFixed(2) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 添加或修改签约合同对话框 -->
    <el-dialog :title="dealName + '-' + oaContractName" :visible.sync="contractFormOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <oaContractForm ref="oaContractForm" />
    </el-dialog>

    <el-dialog
      :title="dealName + $t('-项目收款')"
      :visible.sync="dealCollectionOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
      width="80%"
    >
      <el-table v-loading="dealCollectionLoading" tooltip-effect="darkTable" :data="dealCollectionList" border max-height="600">
        <el-table-column :label="$t('序号')" type="index" align="center" width="50" />
        <el-table-column width="180" :label="$t('款项名称')" align="center" prop="collectionName" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="link-type" @click="updateDealCollectionHandle(scope.row)">{{ scope.row.collectionName }}</span>
          </template>
        </el-table-column>
        <el-table-column width="180" :label="$t('收款条件')" align="center" prop="collectionTerms" show-overflow-tooltip />
        <el-table-column :label="$t('关联合同')" align="center" prop="joinContract" width="180" :formatter="formatContract" show-overflow-tooltip />
        <el-table-column :label="$t('收款时间')" align="center" prop="collectionTime" width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.collectionTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('收款金额') + $t('(万)')" align="center" prop="collectionMoney" width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="money-text">{{ parseFloat(scope.row.collectionMoney / 10000).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('是否开具发票')" align="center" prop="invoice" :formatter="invoiceFormat" width="150" show-overflow-tooltip />
        <el-table-column :label="$t('收款状态')" fixed="right" align="center" prop="collectionState" width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            <span :style="collectionStateColor(scope.row)">{{ collectionStateFormat(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" fixed="right" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['deal:collection:edit']"
              size="small"
              type="text"
              icon="el-icon-edit"
              @click="updateDealCollectionHandle(scope.row)"
            >{{ $t('修改') }}</el-button>
            <el-button
              v-hasPermi="['deal:collection:remove']"
              size="small"
              type="text"
              icon="el-icon-delete"
              @click="deleteDealCollectionHandle(scope.row)"
            >{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加或修改项目收款对话框 -->
    <el-dialog :title="dealName + $t('-项目收款')" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <dealCollectionForm ref="dealCollectionForm" />
    </el-dialog>

    <el-dialog
      :title="dealName + $t('-项目处理情况')"
      :visible.sync="dealProcessingMonthOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
      width="80%"
    >
      <el-table v-loading="dealProcessingMonthLoading" tooltip-effect="darkTable" :show-summary="false" :summary-method="getSummaries" :data="dealProcessingMonthInfoList" border max-height="600">
        <el-table-column :label="$t('')" align="center" prop="personChargeName" min-width="120" show-overflow-tooltip fixed="left">
          <template slot-scope="scope">
            <el-link v-if="scope.row.personCharge" type="primary" @click="findUserDealWeeklyReportRecord(scope.row, null)">
              <span>{{ scope.row.personChargeName }}</span>
            </el-link>
            <span v-else>{{ scope.row.personChargeName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, index) in dealProcessingMonthList"
          :key="index"
          :label="$t(item)"
          align="center"
          min-width="120"
        >
          <template slot-scope="scope">
            <el-link v-if="scope.row.personCharge" class="money-text" type="primary" @click="findUserDealWeeklyReportRecord(scope.row, dealProcessingMonthList[index])">
              <span>{{ parseFloat(scope.row.dealSituationVOList[index] != null ? scope.row.dealSituationVOList[index].workload : 0).toFixed(2) }}</span>
            </el-link>
            <span v-else class="money-text">{{ parseFloat(scope.row.dealSituationVOList[index] != null ? scope.row.dealSituationVOList[index].workload : 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('合计人天')" align="center" prop="workload" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="money-text">{{ parseFloat(scope.row.workload).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('合计成本') + $t('(万)')" align="center" prop="laborCost" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="money-text">{{ parseFloat(scope.row.laborCost / 10000).toFixed(2) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      :title="dealName + '-' + month + userName + $t('周报记录')"
      :visible.sync="dealDealWeeklyReportRecordOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
      width="80%"
    >
      <el-table v-loading="dealDealWeeklyReportRecordLoading" tooltip-effect="darkTable" :data="userDealWeeklyReportRecordList" border max-height="600">
        <el-table-column :label="$t('序号')" type="index" align="center" width="50" />
        <el-table-column :label="$t('用户名称')" align="center" prop="createBy.nickName" width="180" show-overflow-tooltip />
        <el-table-column :label="$t('日期')" align="center" prop="recordDate" width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.recordDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('工作量')" align="center" prop="duration" width="180" show-overflow-tooltip />
        <el-table-column :label="$t('工作内容')" align="center" prop="workCompletion" min-width="300" show-overflow-tooltip />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDealSituation,
  listOaContractList,
  calculationDailyCost,
  listDealCollectionList,
  listDealProcessingMonthList,
  listDealProcessingMonthInfoList,
  listUserDealWeeklyReportRecordList
} from '@/api/anxin/dealsituation/dealSituation'
import dealCollectionForm from '@/views/deal/collection/dealCollectionForm.vue'
import oaContractForm from '@/views/oa/contract/oaContractForm.vue'
import { selectContractToAnxin } from '@/api/oa/contract/oaContract'
import { delDealCollection } from '@/api/deal/collection/dealCollection'
import { moneyFormat } from '@/utils/ruoyi'
// import { getDataListByView } from '@/api/system/search/searchMainView'
export default {
  components: {
    oaContractForm,
    dealCollectionForm
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      oaContractLoading: true,
      dealCollectionLoading: true,
      dealProcessingMonthLoading: true,
      dealDealWeeklyReportRecordLoading: true,
      // 总条数
      total: 0,
      // 项目情况表格数据
      dealSituationList: [],
      // OA合同表格数据
      oaContractList: [],
      // 项目收款表格数据
      dealCollectionList: [],
      // 收款状态字典
      collectionStateOptions: [],
      // 是否开具发票字典
      invoiceOptions: [],
      // 签约时间 查询参数
      initialSigningTimes: [],
      // 关联合同
      contractOptions: [],
      // 项目月份处理情况列表
      dealProcessingMonthInfoList: [],
      // 项目处理月份
      dealProcessingMonthList: [],
      // 用户项目周报处理记录
      userDealWeeklyReportRecordList: [],
      // 项目名称
      dealName: undefined,
      // OA合同名称
      oaContractName: undefined,
      // 用户名称
      userName: undefined,
      // 月份
      month: undefined,
      // 弹出层标题
      title: '项目情况',
      // 是否显示弹出层
      formOpen: false,
      contractOpen: false,
      contractFormOpen: false,
      dealCollectionOpen: false,
      dealCollectionFormOpen: false,
      dealProcessingMonthOpen: false,
      dealDealWeeklyReportRecordOpen: false,
      // 查询参数
      queryParams: {
        dealName: undefined,
        dept: [],
        personCharge: undefined,
        startDate: undefined,
        endDate: undefined,
        prop: undefined,
        order: undefined,
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.getList()
    this.getDicts('invoice_yn').then(response => {
      this.invoiceOptions = response.data
    })
    this.getDicts('collection').then(response => {
      this.collectionStateOptions = response.data
    })
  },
  methods: {
    /**
     * 更新人天成本计算
     */
    calculation() {
      this.loading = true
      return calculationDailyCost().then(() => {
        this.getList()
        this.msgSuccess(this.$t('更新成功'))
      }).catch(() => {
        this.loading = false
      })
    },
    /** 查询系统用户人天成本维护列表 */
    getList() {
      this.loading = true
      // 时间参数赋值
      if (this.initialSigningTimes != null && this.initialSigningTimes.length > 1) {
        this.queryParams.startDate = this.initialSigningTimes[0]
        this.queryParams.endDate = this.initialSigningTimes[1]
      } else {
        this.queryParams.startDate = undefined
        this.queryParams.endDate = undefined
      }
      if (this.queryParams.dept) {
        this.queryParams.dept = this.queryParams.dept.toString()
      }
      listDealSituation(this.queryParams).then(response => {
        this.dealSituationList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dealId: undefined,
        dealName: undefined,
        personCharge: undefined,
        personChargeName: undefined,
        contractQuantity: undefined,
        contractAmount: undefined,
        received: undefined,
        laborCost: undefined,
        profitEst: undefined,
        profitAct: undefined,
        uncollected: undefined,
        badDebt: undefined,
        workload: undefined,
        initialSigningTime: undefined,
        startDate: undefined,
        endDate: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.initialSigningTimes = []
      // 查询参数
      this.queryParams = {
        dealName: undefined,
        dept: [],
        personCharge: undefined,
        startDate: undefined,
        endDate: undefined,
        prop: undefined,
        order: undefined,
        pageNum: 1,
        pageSize: 10
      }
      this.queryHandle()
    },
    /**
     * 查询合同列表
     * @param row
     */
    findContractSituation(row) {
      this.dealName = row.dealName
      this.contractOpen = true
      this.oaContractLoading = true
      listOaContractList(row.dealId).then(response => {
        this.oaContractList = response.rows
        this.oaContractLoading = false
      }).catch(() => {
        this.oaContractLoading = false
      })
    },
    updateOaContractHandle(row) {
      this.oaContractName = row.name
      this.contractFormOpen = true
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.oaContractForm.init(row)
      })
    },
    // 查询项目收款列表
    findCollectionSituation(row, type) {
      this.dealName = row.dealName
      this.dealCollectionOpen = true
      this.dealCollectionLoading = true
      listDealCollectionList(row.dealId, type).then(response => {
        this.dealCollectionList = response.rows
        // 合同
        selectContractToAnxin({ dealId: row.dealId }).then(response => {
          this.contractOptions = []
          response.data.forEach(item => {
            this.contractOptions.push({ dictValue: item.id, dictLabel: item.name })
          })
        })
        this.dealCollectionLoading = false
      }).catch(() => {
        this.dealCollectionLoading = false
      })
    },
    updateDealCollectionHandle(row) {
      this.formOpen = true
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.dealCollectionForm.init(row)
      })
    },
    // 删除项目收款
    deleteDealCollectionHandle(row) {
      // const dealId = row.dealId
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delDealCollection(row.id)
      }).then(() => {
        this.getList()
        this.findCollectionSituation(row)
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {
      })
    },
    // 不同的收款类型返回不同的颜色
    collectionStateColor(item) {
      if (item.collectionState === 'YSK') {
        return { color: 'green' }
      } else if (item.collectionState === 'YWT') {
        return { color: '#FAD033' }
      } else if (item.collectionState === 'HZ') {
        return { color: 'red' }
      } else {
        return ''
      }
    },
    // 收款状态字典翻译
    collectionStateFormat(row) {
      return this.selectDictLabel(this.collectionStateOptions, row.collectionState)
    },
    // 是否开具发票字典翻译
    invoiceFormat(row) {
      return this.selectDictLabel(this.invoiceOptions, row.invoice)
    },
    // 关联合同
    formatContract(row) {
      return this.selectDictLabel(this.contractOptions, row.joinContract)
    },
    queryUserDealWorkloadByMonth(row) {
      this.dealName = row.dealName
      this.dealProcessingMonthOpen = true
      this.dealProcessingMonthLoading = true
      listDealProcessingMonthInfoList(row.dealId).then(response => {
        this.dealProcessingMonthInfoList = response.rows
        listDealProcessingMonthList(row.dealId).then(response => {
          this.dealProcessingMonthList = response.rows
        })
        this.dealProcessingMonthLoading = false
      }).catch(() => {
        this.dealProcessingMonthLoading = false
      })
    },
    // 合计
    getSummaries(param) {
      const {
        columns,
        data
      } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index < 1) {
          sums[index] = '合计'
          return
        } else if (index > 1) {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return moneyFormat(prev + curr, 'w')
              } else {
                return moneyFormat(prev, 'w')
              }
            }, 0)
            sums[index] += '万'
          } else {
            sums[index] = 'N/A'
          }
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 查询用户项目周报处理记录
    findUserDealWeeklyReportRecord(row, month) {
      this.userName = row.personChargeName
      month != null ? this.month = month : this.month = ''
      this.dealDealWeeklyReportRecordOpen = true
      this.dealDealWeeklyReportRecordLoading = true
      listUserDealWeeklyReportRecordList(row.dealId, row.personCharge, month).then(response => {
        this.userDealWeeklyReportRecordList = response.rows
        this.dealDealWeeklyReportRecordLoading = false
      }).catch(() => {
        this.dealDealWeeklyReportRecordLoading = false
      })
    },
    // 排序
    dataSort(column) {
      this.loading = true
      if (column.order !== null && column.order !== undefined && column.order !== '') {
        this.queryParams.prop = column.prop
        if (column.order === 'ascending') {
          this.queryParams.order = 'asc'
        } else if (column.order === 'descending') {
          this.queryParams.order = 'desc'
        }
      } else {
        this.queryParams.prop = undefined
        this.queryParams.order = undefined
      }
      this.getList()
    }
  }
}
</script>
